import PostModel from '@/model/Post.js'
import PostTagsModel from '@/model/PostTags.js'
import LinksModel from '@/model/Links'
import moment from 'moment'
import config from '@/config/index'
import { checkCode, getJWTPayload, rename } from '@/common/utils'
import UserModel from '@/model/User'
import fs from 'fs'
import { v4 as uuidv4 } from 'uuid'
import mkdir from 'make-dir'
import UserCollects from '@/model/UserCollect'
// import { dirExist } from '@/common/utils'

class ContentController {
  async getList (ctx) {
    const body = ctx.query
    const options = {}
    const sort = body.sort ? body.sort : 'created'
    const page = body.page ? parseInt(body.page) : 0
    const limit = body.limit ? parseInt(body.limit) : 20
    if (typeof body.isEnd !== 'undefined' && body.isEnd !== '') {
      options.isEnd = body.isEnd
    }
    if (typeof body.tags !== 'undefined' && body.tags !== '') {
      options.tags = { $elemMatch: { name: body.tags } }
    }
    if (typeof body.isTop !== 'undefined' && body.isTop !== '') {
      options.isTop = body.isTop
    }
    if (typeof body.catalog !== 'undefined' && body.catalog !== '') {
      options.catalog = body.catalog
    }
    const data = await PostModel.getList(options, sort, page, limit)
    const total = await PostModel.getListCount(options)
    ctx.body = {
      code: 200,
      data,
      total,
      msg: '获取文章列表成功'
    }
  }

  // 获取友情链接
  async getLinks (ctx) {
    const data = await LinksModel.find({
      type: 'links'
    })
    ctx.body = {
      code: 200,
      data
    }
  }

  // 获取温馨提醒
  async getTips (ctx) {
    const data = await LinksModel.find({
      type: 'tips'
    })
    ctx.body = {
      code: 200,
      data
    }
  }

  async getTopWeek (ctx) {
    const data = await PostModel.find(
      {
        created: {
          $gte: moment().subtract(7, 'days')
        }
      },
      {
        answer: 1,
        title: 1
      }
    )
      .sort({ answer: -1 })
      .limit(15)
    ctx.body = {
      code: 200,
      data
    }
  }

  // 上传图片
  async upload (ctx) {
    const file = ctx.request.files.file
    const ext = file.name.split('.').pop() // 取出文件后缀
    const dir = `${config.UploadPath}/${moment().format(
      'YYYYMMDD'
    )}`
    await mkdir(dir)
    const fileName = uuidv4()
    const reader = fs.createReadStream(file.path)
    const upstream = fs.createWriteStream(`${dir}/${fileName}.${ext}`)
    // 方法一
    // reader.pipe(write)
    // 方法二
    let totalLength = 0
    reader.on('data', (chunk) => {
      totalLength += chunk.length
      console.log(totalLength)
      if (upstream.write(chunk) === false) {
        reader.pause()
      }
    })
    reader.on('drain', () => {
      reader.resume()
    })
    reader.on('end', () => {
      upstream.end()
    })
    ctx.body = {
      code: 200,
      msg: '上传图片成功',
      data: config.upPath + `/${moment().format('YYYYMMDD')}/${fileName}.${ext}`
    }
  }

  // 添加文章
  async addPost (ctx) {
    const { body } = ctx.request
    const sid = body.sid
    const code = body.code
    const check = await checkCode(sid, code)
    if (check) {
      const obj = await getJWTPayload(ctx.header.authorization)
      const user = await UserModel.findById(obj._id)
      if (user.favs < body.favs) {
        ctx.body = {
          code: 403,
          msg: '用户积分不足，无法发表新帖'
        }
        return
      }
      const post = new PostModel(body)
      post.uid = obj._id
      post.save()
      await UserModel.updateOne({
        _id: obj._id
      }, {
        $inc: {
          favs: -body.favs
        }
      })
      ctx.body = {
        code: 200,
        data: post,
        msg: '发帖成功'
      }
    } else {
      ctx.body = {
        code: 403,
        msg: '验证码错误，请重新输入'
      }
    }
  }

  // 编辑文章
  async editPost (ctx) {
    const { body: { sid, code, title, content, tid } } = ctx.request
    const check = await checkCode(sid, code)
    if (check) {
      const obj = await getJWTPayload(ctx.header.authorization)
      const post = await PostModel.findOne({ _id: tid })
      if (!post) {
        ctx.body = {
          code: 404,
          msg: '帖子不存在'
        }
        return
      }
      if (post.isEnd === 1 || post.uid !== obj._id) {
        ctx.body = {
          code: 403,
          msg: '该用户无权进行操作'
        }
        return
      }
      const res = await PostModel.updateOne({ _id: tid }, {
        title,
        content
      })
      if (res.ok === 1) {
        ctx.body = {
          code: 200,
          msg: '更新成功'
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '更新失败'
        }
      }
    }
  }

  // 管理员更新文章
  async updatePostById (ctx) {
    const { body } = ctx.request
    const res = await PostModel.updateOne({ _id: body._id }, body)
    ctx.body = {
      code: 200,
      data: res,
      msg: '更新成功'
    }
  }

  // 获取文章详情
  async getPostDetail (ctx) {
    const { tid = '' } = ctx.query
    if (!tid) {
      ctx.body = {
        code: 403,
        msg: '文章id不能为空'
      }
      return
    }
    const post = await PostModel.findById(tid)
    if (!post) {
      ctx.body = {
        code: 404,
        msg: '文章不存在或已被删除'
      }
      return
    }
    const obj = await getJWTPayload(ctx.header.authorization)
    let collect = 0
    if (obj) {
      const userCollect = await UserCollects.findOne({
        uid: obj._id,
        tid: post._id
      })
      if (userCollect) {
        collect = 1
      }
    }
    await PostModel.updateOne({ _id: tid }, { $inc: { reads: 1 } })
    const data = rename(post.toJSON(), 'uid', 'user')
    data.collect = collect
    ctx.body = {
      code: 200,
      data,
      msg: 'success'
    }
  }

  async deletePostById (ctx) {
    const { tid } = ctx.query
    const post = await PostModel.findOne({ _id: tid })
    if (!post) {
      ctx.body = {
        code: 404,
        msg: '该帖子不存在'
      }
      return
    }
    await PostModel.deleteOne({ _id: tid })
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  }

  // 获取标签列表
  async getTagsList (ctx) {
    const { page = 0, limit = 10, type = '' } = ctx.query
    let data = []
    if (type === 'all') {
      data = await PostTagsModel.find()
    } else {
      data = await PostTagsModel.getList(page, parseInt(limit))
    }
    const total = await PostTagsModel.getListCount()
    ctx.body = {
      data,
      total,
      code: 200,
      msg: 'success'
    }
  }

  // 保存标签
  async saveTags (ctx) {
    const { body } = ctx.request
    const data = new PostTagsModel(body)
    data.save()
    ctx.body = {
      data,
      code: 200,
      msg: 'success'
    }
  }

  // 更新标签
  async updateTags (ctx) {
    const { body: { _id, name, className } } = ctx.request
    const postTags = await PostTagsModel.findOne({ _id })
    if (!postTags) {
      ctx.body = {
        code: 404,
        msg: '标签不存在，无法更新'
      }
      return
    }
    const data = await PostTagsModel.updateOne({ _id }, { name, className })
    ctx.body = {
      data,
      code: 200,
      msg: '更新成功'
    }
  }

  // 删除标签
  async deleteTags (ctx) {
    const { id } = ctx.request.body
    await PostTagsModel.deleteOne({ _id: id })
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  }
}

export default new ContentController()
